import DeathbillsApi from '../../../common/api/cbs/deathbillslist.api.js';
import doT from '../../../../vendor/template/doT.js';
import { DictionaryType, requestDict } from '../../../common/dictionary/dictionary-type.js';
import { uploadFile, requestFilePath, publicFileDraw, sliceFileName } from '../../../common/api/file-request.js';
import { Select2Info, Select2Page } from '../../../common/serve-request.js';
import { locationService } from '../../../common/locationService.js';

let getEntryInfo = [],
    _pickerTime,
    _vm,
    remedyDate,
    _allUploadFiles = [];
const addsaleTemplate = doT.template($('#addsaleorders-template').text());
(function (window, document, $) {
    const toolbarTemplate = `<div class="toolbar" id="me-date-screening"><div class="toolbar-inner">
<span style='margin:0 auto;margin-top:10px'>请选择业务日期</span><a href="javascript:;" class="picker-button close-picker" style="color:#427ce7;font-size:20px;margin-right:18px;display:inline-block;line-height:100%">{{closeText}}</a></div></div>`;

    $(function () {
        _vm = new Vue({
            el: '#addsaleorders-form',
            data() {
                return {
                    uploadCount: 0,
                    attaches: [],
                    breedBatch: {
                        id: '',
                        name: '',
                    },
                    fiOrg: {
                        id: '',
                        name: '',
                    },
                    farmOrg: {
                        id: '',
                        name: '',
                    },
                    sourceFarm: {
                        id: '',
                        name: '',
                    },
                    supplier: {
                        id: '',
                        name: '',
                        numCode: '',
                    },
                    executor: {
                        id: '',
                        name: '',
                        numCode: '',
                    },
                    remedy: '',
                    bizDate: moment(new Date()).format('YYYY-MM-DD'),
                    deathCode: '',
                    reasonNames: '',
                    remark: '',
                    avgWeight: '',
                    totalCount: '',
                    totalWeight: '',
                    entries: [],
                };
            },
            mounted() {
                let url = location.href;
                let params = {}; // url参数
                for (let key of new URL(url).searchParams.entries()) {
                    key[1] ? (params[key[0]] = key[1]) : '';
                }
                let ids = Utils.GetSessionStorage('ids');
                if (params.id || ids) {
                    document.title = '死亡记录 - 编辑';
                    $('#add-saleEntry').css('display', 'none');
                } else {
                    $('#add-saleEntry').css('display', 'block');
                }
            },
        });
        $('body').attr('data-weui-theme', 'light'); //强制光明模式
        // _datetimePickerInit();
        clickFun();
        _initCommand();
        uploadInit();
    });

    // 附件上传
    const uploadInit = () => {
        weui.uploader('#uploader', {
            url: '',
            auto: false,
            type: 'file',
            compress: { isNoTCompress: true },
            onBeforeQueued: function (files) {
                // if (!isMobile() && files.length > 0) {
                //     $.toptip('请使用手机拍照上传！', 'warning');
                //     return false;
                // }
                if (['image/jpg', 'image/jpeg', 'image/png'].indexOf(this.type) < 0) {
                    $.toptip('请上传图片', 'warning');
                    return false; // 阻止文件添加
                }
                $.showLoading('上传中..');
                _vm.uploadCount = ++_vm.uploadCount;
                if (_vm.uploadCount == 3) {
                    $('.weui-uploader__input-box').hide();
                }
            },
            onQueued: async function () {
                const file = this;
                let suffix = this.name.split('.').pop().toLowerCase(); //截取附件后缀
                let name = this.name.slice(0, 11 - suffix.length - 1); //计算截取文件的11位字符
                let newName = name + '.' + suffix;
                let file1 = publicFileDraw(newName, _vm);
                // 在这里添加日期和地点水印
                const currentDate = moment(new Date()).format('YYYY-MM-DD');
                const currentTime = moment(new Date()).format('HH:mm:ss');
                const locationWatermark = $('#addressInfo').text();
                const canvas = document.createElement('canvas');
                const context = canvas.getContext('2d');
                const image = new Image();
                image.src = window.URL.createObjectURL(file);

                if (!Utils.IsNotNull(locationWatermark)) {
                    $.toptip('定位失败!', 'warning');
                    $.hideLoading();
                    $('#uploaderFiles').last().empty();
                    return;
                }
                image.onload = function () {
                    canvas.width = image.width;
                    canvas.height = image.height;
                    // 在canvas上绘制原始图片
                    context.drawImage(image, 0, 0);

                    // 添加水印，支持换行
                    const watermarkText = currentDate + ' ' + currentTime + '\n' + locationWatermark;
                    context.font = '700 ' + 80 + 'px Arial';
                    context.fillStyle = 'white';

                    // 在指定位置绘制文本
                    const x = 10;
                    const y = image.height - 160;
                    drawWrappedText(context, watermarkText, x, y, 200, 130); // 调用自定义函数

                    // 将canvas转为Blob
                    canvas.toBlob(function (blob) {
                        const formData = new FormData();
                        formData.append('apiobjfile', blob, file1);
                        _uploadFileDraw(formData, file, _vm);
                    }, file.type || 'image/png'); // 使用原始图片的类型或默认为PNG
                };
            },
        });
        $('#uploaderFiles').click(function (e) {
            let target = e.target;
            while (!target.classList.contains('weui-uploader__file') && target) {
                target = target.parentNode;
            }
            if (!target) return;
            //从图片对应的li标签中获得所需属性
            let gallery = weui.gallery($(target).attr('data-url'), {
                className: 'custom-name',
                onDelete: function () {
                    //删除图片的回调
                    $.confirm({
                        title: '删除提示',
                        text: '确定删除该图片？',
                        onOK: function () {
                            let _id = $(target).attr('data-id');
                            _vm.attaches = _vm.attaches.filter((item) => item.id != _id);
                            _vm.uploadCount = --_vm.uploadCount;
                            target.remove();
                            gallery.hide();
                            // 添加3张后隐藏上传按钮
                            if (_vm.uploadCount == 3) {
                                $('.weui-uploader__input-box').hide();
                            } else {
                                $('.weui-uploader__input-box').show();
                            }
                        },
                        onCancel: function () {},
                    });
                },
            });
        });
    };
    // 自定义函数，用于在Canvas上绘制换行的文本
    function drawWrappedText(context, text, x, y, maxWidth, lineHeight) {
        var words = text.split('\n');
        var line = '';
        var yOffset = 0;

        for (var i = 0; i < words.length; i++) {
            var word = words[i];
            var testLine = line + word + ' ';
            var metrics = context.measureText(testLine);
            var testWidth = metrics.width;

            if (testWidth > maxWidth && i > 0) {
                context.fillText(line, x, y + yOffset);
                line = word + ' ';
                yOffset += lineHeight;
            } else {
                line = testLine;
            }
        }

        context.fillText(line, x, y + yOffset);
    }
    function isMobile() {
        return /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);
    }
    // 附件上传
    const _uploadFileDraw = (formFile, upFiles, _vm, newName) => {
        uploadFile(formFile)
            .then(async (res) => {
                if (res.isSucceed) {
                    let imageurl = await requestFilePath(res.data);
                    let _list = _vm.attaches;
                    _list.push({
                        id: $('#uploaderFiles li').length,
                        imageId: res.data,
                        url: imageurl.data,
                    });
                    _vm.attaches = _list;
                    $('#uploaderFiles li').each(function (i) {
                        $(this).attr('data-id', _vm.attaches[i].id);
                        $(this).attr('data-image-id', _vm.attaches[i].imageId);
                        $(this).attr('data-url', _vm.attaches[i].url);
                        $(this).css({ 'background-image': `url(${_vm.attaches[i].url})` });
                    });
                    $('.weui-uploader__file-content').hide();
                    $('.weui-uploader__file').removeClass('weui-uploader__file_status');
                }
            })
            .catch((res) => {
                $('#uploaderFiles li')
                    .eq($('#uploaderFiles li').length - 1)
                    .remove();
                _vm.uploadCount = --_vm.uploadCount;
                $.toptip(res.msg, 'error');
            })
            .finally((_) => {
                $.hideLoading();
                $.closeModal();
            });
    };
    // 编辑回显
    const _images = async (file) => {
        let _imag = file;
        if (_imag) {
            let _sun = 0;
            for (let i = 0; i < _imag.length; i++) {
                ++_sun;
                await requestFilePath(_imag[i].imageId).then((_res) => {
                    _vm.attaches.push({
                        id: _sun,
                        url: _res.data,
                        imageId: _imag[i].imageId,
                    });
                    if (_res.isSucceed) {
                        let _li;
                        _li = `<li class="weui-uploader__file" data-id="${_sun}" data-url="${_res.data}" data-image-id="${_imag[i].imageId}" style="background-image: url(${_res.data}) "></li>`;
                        $('#uploaderFiles').append(_li);
                    }
                });
            }
            if (_sun == 3) {
                $('.weui-uploader__input-box').hide();
            }
            _vm.uploadCount = _sun;
        }
    };
    // 初始化数据
    const _initCommand = async () => {
        // 选择日期
        $('#search-date').on('click', function () {
            pick();
        });
        // 养殖批次
        Select2Info(
            $(`#breddBatchId`),
            `${Utils.CurDomain.BaseCfgUrl}/breedbatchs/cur`,
            (params) => {
                return JSON.stringify({
                    searchInfo: params.term,
                    tags: '',
                });
            },
            'POST',
            {
                allowClear: true, //允许清空
                placeholder: '请选择养殖批次...', //默认文字提示
                templateResult: function (res) {
                    return `${res.name}`;
                },
            },
        );
        $('#breddBatchId').setSelectValue();

        //处理方式
        let type = await requestDict(DictionaryType.DEATH_HANDLING_METOD);
        remedyDate = type.data;
        $('#remedy')
            .empty()
            .select2({
                placeholder: '请选择处理方式...', //默认文字提示
                language: 'zh-CN', //汉化
                allowClear: true, //允许清空
                data: remedyDate.map((item) => {
                    return {
                        id: item.value,
                        text: item.displayName,
                    };
                }),
            });
        $('#remedy').setSelectValue();
        //选择处理方式
        $('#remedy').on('select2:select', async function () {
            let remedyInfo = $('#remedy').select2('data')[0];
            _vm.remedy = remedyInfo.id;
        });
        // 执行人
        Select2Page(
            $(`#executor`),
            `${Utils.CurDomain.EmployeeMgtUrl}/emplrecds/by/q`,
            (params) => {
                return {
                    searchInfo: params.term,
                    pageSize: 10,
                    pageIndex: (params.page || 1) - 1,
                };
            },
            'GET',
            {
                placeholder: '请选择执行人...', //默认文字提示
                language: 'zh-CN', //汉化
                allowClear: true, //允许清空
                templateResult: function (res) {
                    return `${res.name}(${res.numCode})`;
                },
            },
        );
        $(`#executor`).setSelectValue();
        //选择执行人
        $('#executor').on('select2:select', async function () {
            let executorInfo = $('#executor').select2('data')[0];
            _vm.executor = {
                id: executorInfo.id,
                name: executorInfo.name,
                numCode: executorInfo.numCode,
            };
        });

        //选择销售组织带出农场
        $('#breddBatchId')
            .on('select2:select', async function () {
                let breddBatchInfo = $('#breddBatchId').select2('data')[0];
                let sourceInfo;
                try {
                    sourceInfo = await DeathbillsApi.getFormOrg(breddBatchInfo?.id);
                } catch (e) {}
                let breddInfo = {
                    breedBatch: {
                        id: breddBatchInfo.id || '',
                        name: breddBatchInfo.name || '',
                    },
                    fiOrg: {
                        id: breddBatchInfo.fiOrgId,
                        name: breddBatchInfo.fiOrgName,
                    },
                    farmOrg: {
                        id: breddBatchInfo.farmOrgId || '',
                        name: breddBatchInfo.farmOrgName || '',
                    },
                    deathCode: breddBatchInfo.deathCode,
                };
                let sourcesupInfo = {
                    sourceFarm: {
                        id: '',
                        name: sourceInfo[0]?.supplierFarmName,
                    },
                    supplier: {
                        id: sourceInfo[0]?.supplierId,
                        name: sourceInfo[0]?.supplierName,
                        numCode: sourceInfo[0]?.supplierNumCode,
                    },
                };
                _vm.breedBatch = breddInfo.breedBatch;
                _vm.fiOrg = breddInfo.fiOrg;
                _vm.farmOrg = breddInfo.farmOrg;
                _vm.sourceFarm = sourcesupInfo.sourceFarm;
                _vm.supplier = sourcesupInfo.supplier;
                _vm.deathCode = breddInfo.deathCode;
            })
            .on('select2:clear', function () {
                _vm.breedBatch = '';
                _vm.fiOrg = '';
                _vm.farmOrg = '';
                _vm.sourceFarm = '';
                _vm.supplier = '';
                _vm.deathCode = '';
            });

        // 获取主表数据：
        let getMainInfo = JSON.parse(Utils.GetSessionStorage('deliverDatas'));

        if (Utils.IsNotNull(getMainInfo)) {
            _vm.breedBatch = getMainInfo.breedBatch;
            _vm.fiOrg = getMainInfo.fiOrg;
            _vm.farmOrg = getMainInfo.farmOrg;
            _vm.sourceFarm = getMainInfo.sourceFarm;
            _vm.supplier = getMainInfo.supplier;
            _vm.executor = getMainInfo.executor;
            _vm.deathCode = getMainInfo.deathCode;
            _vm.avgWeight = getMainInfo.avgWeight;
            _vm.bizDate = getMainInfo.bizDate;
            _vm.remedy = getMainInfo.remedy;
            _vm.remark = getMainInfo.remark;
            _images(getMainInfo.attaches);
            $(`#executor`).setSelectValue(getMainInfo.executor?.id, getMainInfo.executor?.name);
            $(`#breddBatchId`).setSelectValue(getMainInfo.breedBatch.id, getMainInfo.breedBatch.name);
            $('#remedy').val(getMainInfo.remedy).trigger('change');
        }

        // 编辑
        let ids = getUrlKey('id');
        if (Utils.IsNotNull(ids)) {
            $('#informationSubmit').text('保存');
            $('title').text('死亡记录 - 编辑');
            await DeathbillsApi.getDeathList(ids).then((res) => {
                _vm.breedBatch = res.breedBatch;
                _vm.fiOrg = res.fiOrg;
                _vm.farmOrg = res.farmOrg;
                _vm.sourceFarm = res.sourceFarm;
                _vm.supplier = res.supplier;
                _vm.executor = res.executor;
                _vm.deathCode = res.deathCode;
                _vm.avgWeight = res.avgWeight;
                _vm.bizDate = moment(res.bizFormObj.bizDate).format('YYYY-MM-DD');
                _vm.remedy = res.remedy;
                _vm.remark = res.remark;
                _vm.totalCount = _vm.totalCount;
                _vm.totalWeight = _vm.totalWeight;
                $(`#executor`).setSelectValue(res.executor?.id, res.executor?.name);
                $(`#breddBatchId`).setSelectValue(res.breedBatch.id, res.breedBatch.name);
                $('#remedy').val(res.remedy).trigger('change');
                res.deathInfo.forEach((item, index) => {
                    item.seq = index;
                });
                JSON.stringify(Utils.SetSessionStorage('getEntryInfo', res.deathInfo));
                $('#salesEntry').empty().append(addsaleTemplate(res.deathInfo));
                JSON.stringify(Utils.SetSessionStorage('ids', ids));

                let editImage = [];
                if (Utils.IsNotNull(res.attaches)) {
                    res.attaches.split(',').forEach((item) => {
                        editImage.push({
                            imageId: item,
                        });
                    });
                    _images(editImage);
                }
            });
        }

        // 获取分录信息
        getEntryInfo = JSON.parse(Utils.GetSessionStorage('getEntryInfo'));
        // 渲染 分录
        if (Utils.IsNotNull(getEntryInfo)) {
            $('#salesEntry').empty().append(addsaleTemplate(getEntryInfo));
            let totalCount = 0,
                allresion = [];
            getEntryInfo.map((item) => {
                totalCount += Number(item.count);
                allresion.push(item.reasionName);
            });
            _vm.reasonNames = allresion.join(',');
            _vm.totalCount = totalCount;
            _vm.totalWeight = Utils.toThousands(Number(_vm.avgWeight) * Number(_vm.totalCount), 2);
            let ids = Utils.GetSessionStorage('ids');
            if (Utils.IsNotNull(ids)) {
                $('.hideStyle').attr('hidden', 'hidden');
            }
        }
        $('#avgWeight').on('change', function () {
            _vm.totalWeight = Utils.toThousands(Number(_vm.avgWeight) * Number(_vm.totalCount), 2);
        });
    };

    const pick = () => {
        weui.datePicker({
            defaultValue: moment(new Date()).format('YYYY-MM-DD').split('-'),
            end: moment(new Date()).format('YYYY-MM-DD'),
            className: 'mypick',
            onConfirm: async function (result) {
                //let value = `${result[0].value}-${result[1].value}-${result[2].value}`;
                //_vm.bizDate = moment(new Date(value)).format('YYYY-MM-DD')

                _vm.bizDate = result.map((item) => item.value).join('-');
            },
        }); // 默认配置
    };

    // //业务日期控件初始化
    // const _datetimePickerInit = () => {
    //     initCurrentDay()
    //     $('.sn-drop-down').on('click', function (e) {
    //         e.stopPropagation();
    //     });
    //     // 开始日期
    //     $('#search-date').on('click', function (e) {
    //         e.stopPropagation();
    //         $("#search-date").picker("open");
    //         _pickerDate();
    //     });
    //     $("#search-date").datetimePicker(
    //         {
    //             toolbarTemplate: toolbarTemplate,
    //             toolbarCloseText: "确定",
    //             toolbarCancelText: "取消",
    //             yearSplit: '年',
    //             monthSplit: '月',
    //             dateSplit: '日',
    //             times: function () {
    //                 return [];
    //             },
    //             //确定选择时的操作
    //             onClose: function (picker) {
    //                 let value = picker.value[0] + '-' + picker.value[1] + '-' + picker.value[2];
    //                 _pickerTime = '';
    //                 _pickerTime = value;
    //             }
    //         }
    //     );
    // }

    // //业务日期确认事件
    // const _pickerDate = () => {
    //     $(document).on("click", ".close-picker", function () {
    //         $('#businessTime').val(_pickerTime);
    //         _vm.bizDate = _pickerTime
    //     });
    // }
    // // 业务日期获取当天
    // const initCurrentDay = () => {
    //     let todayDate = moment().format('YYYY-MM-DD')
    //     $('#businessTime').val(todayDate)
    //     _vm.bizDate = todayDate
    // }
    // 保存分录以上的内容
    const storeSession = () => {
        let _mainInfo = {
            ...{ breedBatch: _vm.breedBatch },
            ...{ fiOrg: _vm.fiOrg },
            ...{ farmOrg: _vm.farmOrg },
            ...{ sourceFarm: _vm.sourceFarm },
            ...{ supplier: _vm.supplier },
            ...{ executor: _vm.executor },
            deathCode: _vm.deathCode,
            remedy: _vm.remedy,
            bizDate: _vm.bizDate,
            remark: _vm.remark,
            avgWeight: _vm.avgWeight,
            totalCount: _vm.totalCount,
            totalWeight: _vm.totalWeight,
            reasonNames: _vm.reasonNames,
            attaches: _vm.attaches,
        };
        let deliverDatas = { ..._mainInfo };
        // 保存数据内容
        Utils.SetRouterState('deliverDatas', deliverDatas);
    };

    // 操作函数
    const clickFun = () => {
        //取消按钮，返回列表
        $(document).on('click', '#returnMain', function () {
            // 删除分录 删除页面数据 删除ID
            window.sessionStorage.removeItem('getEntryInfo');
            window.sessionStorage.removeItem('deliverDatas');
            window.sessionStorage.removeItem('ids');
            location.href = `../deathbills/deathbillslist.html?v=${Utils.GetTime()}`;
        });

        //取消，关闭弹框
        $(document).on('click', '#returnAddSaleOrders', function () {
            $('#pop').css('display', 'none');
            $('.show-box').css('display', 'none');
            $('.show-box').css({
                bottom: '-6rem',
                transition: 'all .ls ease-in',
            });
        });

        // 点击分录
        $('#add-saleEntry').on('click', function (e) {
            // 存储数据
            storeSession();
            // 获取分录 否则 默认是0
            let index = JSON.parse(Utils.GetSessionStorage('getEntryInfo'))?.length || 0;
            location.href = `../deathbills/deathbillsentry.html?v=${Utils.GetTime()}&orgId=${_vm.saleOrgId}&index=${index}&isEdit=${false}`;
        });

        // 提交数据
        $('#informationSubmit').on('click', function (e) {
            let entries = JSON.parse(Utils.GetSessionStorage('getEntryInfo'));
            if (!Utils.IsNotNull(_vm.breedBatch?.id)) {
                return $.toptip(`请选择养殖批次!`, 'warning');
            }
            if (!Utils.IsNotNull(_vm.avgWeight)) {
                return $.toptip(`请输入死亡均重!`, 'warning');
            }
            if (!Utils.IsNotNull(_vm.remedy)) {
                return $.toptip(`请选择处理方式!`, 'warning');
            }
            if (!Utils.IsNotNull(_vm.executor?.id)) {
                return $.toptip(`请选择执行人!`, 'warning');
            }
            var reg = /^(?!0+(?:\.0+)?$)(?:[1-9]\d*|0)(?:\.\d{1,2})?$/;
            if (!reg.test(_vm.avgWeight)) return $.toptip(`死亡均重必须大于0并且只能保留两位小数`, 'warning');

            if (!Utils.IsNotNull(entries)) {
                return $.toptip(`请添加死亡记录分录信息!`, 'warning');
            }
            let arry = [];
            for (var i = 0; i < entries.length; i++) {
                arry.push(entries[i].reasion);
            }
            // if (new Set(arry).size !== arry.length) {
            //     return $.toptip(`死亡原因重复，请重新选择!`, 'warning');
            // }
            savetips();
        });

        // 删除分录
        $(document).on('click', '#salesEntry div[data-flag=table-click-delete]', function () {
            let seq = $(this).data('index');
            $.modal({
                autoClose: false,
                title: '删除提示',
                text: `<div class="weui-cells__group weui-cells__group_form" style="margin-top:-5px">
					<div class="" style="padding:5px;display:flex;justify-content: center; padding-bottom: 20px;">
						<div>是否确认删除该分录?</div>
					</div>`,
                buttons: [
                    {
                        text: '取消',
                        className: 'default',
                        onClick: function () {
                            $.closeModal();
                        },
                    },
                    {
                        text: '确定',
                        onClick: function () {
                            // 过滤
                            let datas = getEntryInfo.filter((item) => item.seq != seq);
                            // 重置seq
                            let info =
                                datas.map((item, index) => {
                                    item.seq = index;
                                    return item;
                                }) || [];

                            // 赋值
                            JSON.stringify(Utils.SetSessionStorage('getEntryInfo', info));
                            $('#salesEntry').empty().append(addsaleTemplate(info));
                            let totalCount = 0,
                                allresion = [];
                            info.map((item) => {
                                totalCount += Number(item.count);
                                allresion.push(item.reasionName);
                            });
                            _vm.reasonNames = allresion.join(',');
                            _vm.totalCount = totalCount;
                            _vm.totalWeight = Utils.toThousands(Number(_vm.avgWeight) * Number(totalCount), 2);
                            $.closeModal();
                        },
                    },
                ],
            });
        });

        // 编辑
        $(document).on('click', '#salesEntry div[data-flag=table-click-edit]', function () {
            // 存储数据
            storeSession();
            // 获取分录 否则 默认是0
            let index = $(this).data('index');
            location.href = `../deathbills/deathbillsentry.html?v=${Utils.GetTime()}&orgId=${_vm.saleOrgId}&index=${index}&isEdit=${true}`;
        });
    };
    // 保存
    const savetips = () => {
        $.modal({
            autoClose: false,
            title: '提示',
            text: `<div class="weui-cells__group weui-cells__group_form" style = "margin-top:-5px" >
                    <div class="addedientry" style="padding:5px;display:flex;justify-content: center; padding-bottom: 20px;">
                        <div class="addentry" >是否确认保存该单据？</div>
                    </div> 
                    </div>`,
            buttons: [
                {
                    text: '取消',
                    className: 'default',
                    onClick: function () {
                        $.closeModal();
                    },
                },
                {
                    text: '保存',
                    onClick: function () {
                        $.closeModal();
                        let ids = Utils.GetSessionStorage('ids');
                        let entries = JSON.parse(Utils.GetSessionStorage('getEntryInfo'));
                        let imageArr = [];
                        _vm.attaches.forEach((item) => {
                            imageArr.push(item.imageId);
                        });
                        let attachesStr = imageArr.join(',');
                        let datas = {
                            ...{ breedBatch: _vm.breedBatch },
                            ...{ fiOrg: _vm.fiOrg },
                            ...{ farmOrg: _vm.farmOrg },
                            ...{ sourceFarm: _vm.sourceFarm },
                            ...{ supplier: _vm.supplier },
                            ...{ executor: _vm.executor },
                            deathCode: _vm.deathCode,
                            remedy: _vm.remedy,
                            bizDate: moment(new Date(_vm.bizDate)).format('YYYY-MM-DD'),
                            remark: _vm.remark,
                            avgWeight: _vm.avgWeight,
                            totalCount: _vm.totalCount,
                            totalWeight: _vm.totalWeight,
                            reasonNames: _vm.reasonNames,
                            DeathInfo: [...entries],
                            billType: 4,
                            attaches: attachesStr,
                        };
                        if (Utils.IsNotNull(ids)) {
                            return DeathbillsApi.editFatDeath(ids, JSON.stringify(datas)).then((res) => {
                                $.toptip('请求成功。', 'success');
                                // 延时一秒跳转  要看提示
                                setTimeout(function () {
                                    window.sessionStorage.removeItem('getEntryInfo');
                                    window.sessionStorage.removeItem('deliverDatas');
                                    window.sessionStorage.removeItem('ids');
                                    location.href = `../deathbills/deathbillslist.html?v=${Utils.GetTime()} `;
                                }, 1000);
                            });
                        } else {
                            DeathbillsApi.addFatDeath(JSON.stringify(datas)).then(
                                (res) => {
                                    $.toptip('请求成功。', 'success');
                                    // 延时一秒跳转  要看提示
                                    setTimeout(function () {
                                        window.sessionStorage.removeItem('getEntryInfo');
                                        window.sessionStorage.removeItem('deliverDatas');
                                        location.href = `../deathbills/deathbillslist.html?v=${Utils.GetTime()} `;
                                    }, 1000);
                                },
                                (err) => {
                                    $.toptip(err.responseJSON?.msg, 'error');
                                },
                            );
                        }
                    },
                },
            ],
        });
    };

    // 获取地址栏的 参数
    const getUrlKey = (name) => {
        var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;
    };
})(window, document, jQuery);
